import fs from 'node:fs'
import Yaml from 'yaml'
logger.info('奴隶市场载入中...')

fs.mkdirSync('plugins/Slave-Market/data/player', { recursive: true })
fs.mkdirSync('data/Ts-GameData', { recursive: true })
const files = fs.readdirSync('./plugins/Slave-Market/apps').filter(file => file.endsWith('.js'))

// 默认配置
const defaultConfig = {
  buyBack: {
    cooldown: 86400,
    maxTimes: 3,
    taxRate: 0.05
  },
  rob: {
    cooldown: 600,
    successRate: 0.3,
    penalty: 0.1
  },
  work: {
    cooldown: 3600,
    slaveownerCooldown: 60
  },
  purchase: {
    cooldown: 3600
  },
  bank: {
    initialLimit: 1000,
    initialLevel: 1,
    upgradePriceMulti: 1.2,
    limitIncreaseMulti: 1.25,
    initialUpgradePrice: 100
  }
}

// 检查并更新配置文件
function updateConfig() {
  const configPath = 'config/SlaveMarket_config.yaml'
  let config = {}

  // 如果配置文件存在，读取它
  if (fs.existsSync(configPath)) {
    try {
      config = Yaml.parse(fs.readFileSync(configPath, 'utf8'))
    } catch (e) {
      logger.error('配置文件读取失败，将使用默认配置')
      config = {}
    }
  }

  // 递归合并配置
  const mergeConfig = (target, source) => {
    for (const key in source) {
      if (typeof source[key] === 'object' && !Array.isArray(source[key])) {
        target[key] = target[key] || {}
        mergeConfig(target[key], source[key])
      } else if (!(key in target)) {
        target[key] = source[key]
      }
    }
  }

  // 将默认配置合并到现有配置中
  mergeConfig(config, defaultConfig)

  // 写入更新后的配置
  try {
    fs.writeFileSync(configPath, Yaml.stringify(config))
    logger.info('配置文件更新成功')
  } catch (e) {
    logger.error('配置文件写入失败:', e)
  }
}

// 执行配置更新
updateConfig()

let ret = []

files.forEach((file) => {
  ret.push(import(`./apps/${file}`))
})

ret = await Promise.allSettled(ret)

let apps = {}
for (let i in files) {
  let name = files[i].replace('.js', '')

  if (ret[i].status != 'fulfilled') {
    logger.error(`载入插件错误：${logger.red(name)}`)
    logger.error(ret[i].reason)
    continue
  }
  apps[name] = ret[i].value[Object.keys(ret[i].value)[0]]
}

export { apps }
logger.mark('奴隶市场载入成功')
